package com.xh.demo.datasource.aspect;

import com.xh.demo.datasource.ThreadLocalRouteDataSource;
import com.xh.demo.datasource.annotation.LakeDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Aspect
@Order(Ordered.LOWEST_PRECEDENCE - 1)
@Component
public class LakeDataSourceAspect {

    @Pointcut("@annotation(com.xh.demo.datasource.annotation.LakeDataSource)")
    public void lakeDataSource() {

    }

    @Around("lakeDataSource()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        LakeDataSource dataSource = getDataSource(point);
        //设置数据源
        if (dataSource != null) {
            ThreadLocalRouteDataSource.setDataSourceKey(dataSource.value());
        }
        try {
            return point.proceed();
        } finally {
            // 销毁数据源 在执行方法之后
            ThreadLocalRouteDataSource.clear();
        }
    }

    /**
     * 获取需要切换的数据源
     */
    public LakeDataSource getDataSource(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        LakeDataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), LakeDataSource.class);
        if (Objects.nonNull(dataSource)) {
            return dataSource;
        }
        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), LakeDataSource.class);
    }

}